# coding: utf-8
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from common.overwrites import z_render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required

from django.conf import settings
from common.models import User
from common.models.position import JPositionCounty, JPositionTown, JPositionVillage


@login_required
@csrf_exempt
def user_info(request):
    user = request.user
    return z_render_to_response('user_info.html', {'user': user, 'user_profile': user.userprofile})


@login_required
@csrf_exempt
def add_info(request):
    if request.method == 'GET':
        county_list = JPositionCounty.objects.filter(city_id=settings.XINYU_CITY_ID)
        return z_render_to_response('add_info.html', {'user': request.user, 'county_list': county_list})
    if request.method == 'POST':
        user_profile = request.user.userprofile
        county_id = request.POST.get('county_id')
        town_id = request.POST.get('town_id')
        village_id = request.POST.get('village_id')

        avatar = request.FILES.get('avatar')
        declaration = request.POST.get('declaration')

        if county_id:
            user_profile.county = JPositionCounty.objects.get(county_id=int(county_id))
        if town_id:
            user_profile.town = JPositionTown.objects.get(town_id=int(town_id))
        if village_id:
            user_profile.village = JPositionVillage.objects.get(village_id=int(village_id))

        user_profile.avatar = avatar
        user_profile.declaration = declaration
        user_profile.save()
        return HttpResponseRedirect('/user/info')


@login_required
@csrf_exempt
def user_detail(request):
    if request.method == 'GET':
        user = User.objects.get(id=int(request.GET.get('user_id')))
        if hasattr(user, 'userprofile'):
            userprofile = user.userprofile
        else:
            userprofile = None
        return z_render_to_response('user_detail.html', {'user': user, 'user_profile': userprofile})
